
/**
 * DatePicker
 * @author: Dennis Hall
 * @date: 10/01/2009
 * @description: provides datepicker function-ality.
 * @requires: klik plugin (found in foo.global.js)
 */

foo.mod.datepicker = {
	init: function(pickerInputs){
		foo.log('foo.datepicker.init');

		var $ = jQuery, //in case we are using jquery.noconflict()
			calendarIcons = $('.calendar-icon'),
			monthNames = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','),
			daysInMonth = [31,0,31,30,31,30,31,31,30,31,30,31];

		pickerInputs.each(function(i){
			var date = new Date(),
				input = $(this),
				trigger = calendarIcons.eq(i),
				triggerOffset = trigger.offset(),
				pickerContainer = $('<div class="datepicker-container"/>').appendTo('body').hide();

			function show(){
				triggerOffset = trigger.offset();
				pickerContainer.css({'left':triggerOffset.left+trigger[0].offsetWidth, 'top':triggerOffset.top}).show();
			}

			trigger.klik(function(){
				if(pickerContainer.is(':visible')){
					pickerContainer.hide();
				} else {
					drawCalendar(date.getMonth(), date.getFullYear());
					show();
				}
			});

			input.focus(function(){
				drawCalendar(date.getMonth(), date.getFullYear());
				show();
				this.blur();
			});

			function zeropad(n){
				return n < 10 ? '0' + n : n;
			}

			function drawCalendar(m, y){

				// "todayDate" is only used to calculate todaysDayOfMonth
				var todayDate = new Date(),
					// todaysDayOfMonth shall be 0 if we are showing a month other than the month in which today falls.
					todaysDayOfMonth = (y == todayDate.getFullYear() && m == todayDate.getMonth()) ? todayDate.getDate() : 0,
					// fix date bug when current day is 31st
					oD = new Date(y, m, 1),
					firstDayOfMonth = oD.getDay() + 1;

				// fix daysInMonth for February
				daysInMonth[1] = ((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0) ? 29 : 28;

				// build datepicker markup
				var t =' <div class="ie6bg"/><a class="close" href="#"><span class="ie6bg"/>close</a><div class="title">Select a Date</div><div class="month"><a class="prev" href="#" title="Previous month"><img src="css/images/btn-datepicker-prev.gif" alt="Previous month"/></a> <span class="month-name">'+monthNames[m]+' - '+y+'</span> <a class="next" href="#" title="Next month"><img src="css/images/btn-datepicker-next.gif" alt="Next month"/></a></div><table cellpadding="0" cellspacing="0"><tr>';
				for(s=0; s<7; s++){
					t += '<th>'+"SMTWTFS".substr(s,1)+'</th>';
				}
				t += '</tr><tr>';
				for(i=1; i<=42; i++){
					var x = ((i-firstDayOfMonth>=0)&&(i-firstDayOfMonth<daysInMonth[m]))? i-firstDayOfMonth+1 : '&nbsp;';
					if(x == '&nbsp;' && i>8 && i%7==1){ //if we're beginning a blank row at the bottom, don't.
						break;
					}
					t += '<td class="'+(x==todaysDayOfMonth?' today':'')+(i%7==0?' last':'')+'" tabindex="'+(200+i)+'"><div>'+x+'</div></td>';
					if((i%7==0) && (i<36)){
						t += '</tr><tr'+(i==35?' class="last"':'')+'>';
					}
				}
				t += '</tr></table>';

				// write the datepicker to the datepicker-container
				pickerContainer.html(t);

				// (re)add TD behaviors: hover and click

				// reference functions
				function highlight(){
					if($(this).html().indexOf('&nbsp;')<0){
						$(this).addClass('over');
					}
				}
				function unhighlight(){
					$(this).removeClass('over');
				}

				// actual (re)wiring
				pickerContainer.find('td')
					// add hover-ability to the TDs
					.hover(highlight, unhighlight)
					.focus(highlight)
					.blur(unhighlight)

					// add click-ability to the TDs
					.klik(function(){
						if($(this).html().indexOf('&nbsp;')<0){
							input.val( zeropad(m+1) + '/' + zeropad($('div',this).html()) + '/' + (''+y).substr(2) );
							pickerContainer.hide();
						}
					});
				///

				// (re)wire the close link
				pickerContainer.find('.close').klik(function(){
					pickerContainer.hide();
					return false;
				});

				// (re)wire the prev month link
				pickerContainer.find('.prev').klik(function(){
					m--;
					if(m < 0){
						m = 11;
						y--;
					}
					drawCalendar(m, y);
					return false;
				});

				// (re)wire the next month link
				pickerContainer.find('.next').klik(function(){
					m++;
					if(m > 11){
						m = 0;
						y++;
					}
					drawCalendar(m, y);
					return false;
				});

				pickerContainer.find('.today').focus();

			}

		}); //end each

	}
};
